package com.tengfei.broadcastreceiverdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private TextView mTv;

    private BatteryLevelReceiver batteryLevelReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTv = findViewById(R.id.bty_level);
        registerBroadcastReceiver();
    }

    private void registerBroadcastReceiver() {
        // 2.接收电量的变化
        IntentFilter intentFilter = new IntentFilter();
        // 3.设置频道
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
        intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        // 4.实例化广播接收者
        batteryLevelReceiver = new BatteryLevelReceiver();
        // 5.注册广播
        this.registerReceiver(batteryLevelReceiver, intentFilter);

    }

    // 1.创建一个广播接收者
    private class BatteryLevelReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                Log.d("battery", "接受到了电量变化：" + action);
                int intExtra = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                Log.d("battery", "电量为：" + intExtra);
                if (mTv != null) {
                    mTv.setText("当前电量：" + intExtra);
                }
                int maxLevel = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
                Log.d("battery", "当前电量：" + maxLevel);
            } else if (Intent.ACTION_POWER_CONNECTED.equals(action)) {
                Log.d("battery", "USB线连接上了");
            } else if (Intent.ACTION_POWER_DISCONNECTED.equals(action)) {
                Log.d("battery", "USB线拔下来了");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消广播注册
        if (batteryLevelReceiver != null) {
            this.unregisterReceiver(batteryLevelReceiver);
        }
    }
}